package com.itheima05;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author Xiao
 * @date 2021/7/24
 */
public class IteratorDemo01 {
    /**
     *  创建一个集合，有元素a,b,c,d，使用循环遍历这个集合，判断当前获取到的元素是否为b，如果是就删除。
     */
    public static void main(String[] args) {
        ArrayList<String> c = new ArrayList<>();
        c.add("a");
        c.add("b");
        c.add("c");
        c.add("d");
        c.add("d");
        System.out.println(c);
        System.out.println("-------------");
//        method1(c);   //[a, b, c]
        method2(c);     //[a, b, c, d]
//        method3(c);   //[a, b, c]
        System.out.println(c);
    }

    private static void method3(ArrayList<String> c) {
        for (int i = 0; i < c.size(); i++) {
            if ("d".equals(c.get(i))) {
                c.remove(i);
                i--;
            }
        }
    }
    private static void method2(Collection<String> c) {
        for (String s : c) {
            if (s.equals("d")) {
                c.remove(s);
            }
        }
    }
    private static void method1(Collection<String> c) {
        Iterator<String> i = c.iterator();
        while (i.hasNext()) {
            if (i.next().equals("d")) {
//                ConcurrentModificationException   并发修改异常
//                c.remove(i.next());
                i.remove();
            }
        }
    }
}
